﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Excel = Microsoft.Office.Interop.Excel;
using System.Windows.Threading;
using System.Windows;
using TestVisioCanvas.Models;
using System.Runtime.InteropServices;

namespace TestVisioCanvas.Helpers
{
    public class ExcelHelper
    {
        Excel.Application xcl = null;
        object missingValue = System.Reflection.Missing.Value;
        private static float RowHeight = 99;
        private static double ColumnWidth = 13.5;
        

        private Excel.Application StartExcel()
        {
            if (xcl == null)
            {
                try
                {
                    xcl = (Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");                    
                }
                catch (System.Runtime.InteropServices.COMException ex)
                {
                    xcl = new Excel.Application();
                }
            }
            else
            {
                return xcl;
            }

            return xcl;
        }

        public void CreateExcelWorkbook(ApplicationState.AppStateManager State)
        {
            Excel.Workbook wbook;
			Excel.Worksheet wsheet;	
		    
            

            try
            {
                //Start Excel and get Application object.
                if (xcl==null)
                    xcl = StartExcel();

                //xcl.WindowActivate += (wb, wn) =>
                //{
                //    Dispatcher.BeginInvoke(new Action(() =>
                //    App.Current.MainWindow.WindowState = WindowState.Minimized));
                //};
                //xcl.WindowDeactivate += (wb, wn) =>
                //{
                //    Dispatcher.BeginInvoke(new Action(() =>
                //    App.Current.MainWindow.WindowState = WindowState.Maximized));
                //};

               // xcl = new Excel.Application();
                                
                wbook = xcl.Workbooks.Add(
                    Environment.CurrentDirectory+
                    TestVisioCanvas.Resources.Strings.TemplateExcelFolder +
                    State.ExcelTemplateFileName);
                //wbook.Worksheets[2].Delete();
                //wbook.Worksheets[3].Delete();
                var pages = State.PagesAsEnumerable.ToArray();
                wsheet = (Excel.Worksheet)wbook.Worksheets.get_Item(1);
                xcl.ActiveWindow.SplitRow = 11;
                for (int i = 0; i < pages.Length - 1; i++)
                {
                    wsheet.Copy(missingValue, wsheet);
                    xcl.ActiveWindow.SplitRow = 11;
                }
                for (int pageIndex = 0; pageIndex < State.PagesCount; pageIndex++)
                {                    
                    wsheet = (Excel.Worksheet)wbook.Worksheets.get_Item(pageIndex + 1);                    

                    wsheet.Name = pages[pageIndex].PageName;                    

                    var bla = xcl.ActiveSheet.Pictures;

                    #region Commented Code
                    //.Insert(Environment.CurrentDirectory + "/Images/Drawing/background.png");

                    //wsheet.Cells[2, 2] = "Passamonti SRL";
                    //wsheet.Rows[2].Font.Bold = true;
                    //wsheet.Rows[2].Font.Size = 14;

                    //wsheet.Cells[2, 4] = "Preventivo Ufficio";
                    //wsheet.Cells[2, 5] = State.CustomerName;
                    //wsheet.Rows[3].Font.Bold = true;
                    //wsheet.Rows[3].Font.Size = 12;
                    //wsheet.Cells[3, 2] = "Produttore";
                    //wsheet.Cells[3, 3] = "Nome Prodotto";
                    //wsheet.Cells[3, 4] = "Prezzo Unitario";
                    //wsheet.Cells[3, 5] = "Quantità";
                    //wsheet.Cells[3, 6] = "Costo Totale";
                    
                    #endregion                    
                    
                    int StartingRow = State.ExcelTemplateStartingRow;
                    int lastRow=StartingRow;
                    //for (int i = 0; i < VM.SelectedProducts.Count; i++)
                    for (int i = 0; i < pages[pageIndex].SelectedProducts.Count; i++)
                    {   
                        InvoiceModel invoice = pages[pageIndex].SelectedProducts[i];
                        Excel.Range r = wsheet.get_Range("A" + (1).ToString(), "A" + (StartingRow-1).ToString());
                        
                        System.Drawing.Image image = System.Drawing.Bitmap.FromFile(Environment.CurrentDirectory +
                            invoice.Product.ProductDetails.ImagePath);
                        float maxDim = Math.Max(image.Width, image.Height);
                        float ratio = RowHeight / maxDim;
                        Excel.Shape ProductImage=
                        wsheet.Shapes.AddPicture(Environment.CurrentDirectory + invoice.Product.ProductDetails.ImagePath, 
                             Microsoft.Office.Core.MsoTriState.msoFalse,
                             Microsoft.Office.Core.MsoTriState.msoCTrue, 
                             (r.Width-(ratio*image.Width))/2,
                             r.Height +(RowHeight - (ratio * image.Height)) / 2,
                        ratio*image.Width, ratio * image.Height);                        
                        
                        //#region inserimento immagine
                                          
                        //Excel.Range r = wsheet.get_Range("A" + (StartingRow).ToString(), "A" + (StartingRow).ToString());
                        //System.Drawing.Image image = System.Drawing.Bitmap.FromFile(Environment.CurrentDirectory +
                        //invoice.Product.ProductDetails.ImagePath);
                        ////VM.SelectedProducts[i].Product.ProductDetails.ImagePath);

                        //double maxDim = Math.Max(image.Width, image.Height);
                        //double ratio = 99 / maxDim;
                        //int new_width = (int)(image.Width * ratio);
                        //int new_height = (int)(image.Height * ratio);

                        //System.Drawing.Bitmap resizedImage = new System.Drawing.Bitmap(new_width, new_height);
                        //System.Drawing.Graphics g = System.Drawing.Graphics.FromImage((System.Drawing.Image)resizedImage);
                        //g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
                        ////g.DrawImage(image, 0, 0, new_width, new_height);
                        //int w = (int)r.Width;
                        //int h = (int)r.Height;
                        //g.DrawImage(image, 0, 0, (int)r.Width, (int)r.Height);
                        
                        //Clipboard.SetDataObject(resizedImage,false);
                        //int cycle_counter = 20;
                        //while (cycle_counter>0 && !Clipboard.ContainsImage())
                        //{
                        //    System.Threading.Thread.Sleep(50);
                        //    cycle_counter--;
                        //}
                        //if (cycle_counter > 0)
                        //{
                        //    System.Threading.Thread.Sleep(300);
                        //    wsheet.Select();
                        //    r.Select();
                        //    wsheet.Paste(missingValue, missingValue);
                        //    Clipboard.Clear();
                        //}
                        
                        ////System.Threading.Thread.Sleep(300);
                        //// corrispondente di 99 pixel per le righe e le colonne
                        ////r.EntireRow.RowHeight = 76;
                        ////r.EntireColumn.ColumnWidth = 13.5;                        
                        //#endregion
                        wsheet.Cells[StartingRow, 2] = invoice.Product.ProductDetails.Description;
                        wsheet.Cells[StartingRow, 3] = invoice.Quantity;
                        wsheet.Cells[StartingRow, 4] = invoice.Product.ProductDetails.PriceNoVAT;
                        wsheet.Cells[StartingRow, 5] = "=C" + StartingRow.ToString() + "* D" + StartingRow.ToString();
                        //wsheet.Cells[StartingRow + i, 2] = invoice.Product.ProductDetails.Manufacturer;
                        //wsheet.Cells[StartingRow + i, 3] = invoice.Product.ProductDetails.ProductName;
                        //wsheet.Cells[StartingRow + i, 3] = invoice.Product.ProductDetails.ProductName;
                        //wsheet.Cells[StartingRow + i, 4].NumberFormat = "#.##0,00€";
                        //wsheet.Cells[StartingRow + i, 4] = invoice.Product.ProductDetails.PriceNoVAT;
                        //wsheet.Cells[StartingRow + i, 5] = invoice.Quantity;
                        //wsheet.Cells[StartingRow + i, 6].NumberFormat = "#.##0,00€";
                        ////wsheet.Cells[5 + i, 6] = VM.SelectedProducts[i].TotalCost;
                        //wsheet.Cells[StartingRow + i, 6] = "=D" + (5 + i).ToString() + "* E" + (5 + i).ToString();
                        wsheet.Rows[StartingRow].Autofit();
                        

                        Excel.Range selected = wsheet.Rows[StartingRow];
                            //wsheet.get_Range("A" + lastRow.ToString(), "A" + lastRow.ToString());
                        selected.Insert(Excel.XlInsertShiftDirection.xlShiftDown, missingValue);
                        selected.RowHeight = Math.Max(selected.RowHeight, RowHeight);
                        
                        lastRow++;
                        
                        //r =
                        //    wsheet.get_Range("B" + lastRow.ToString(), "B" + lastRow.ToString());
                        //r.Select();
                        //r.AutoFit();
                        ProductImage.Placement = Excel.XlPlacement.xlMoveAndSize;
                    }

                    wsheet.Rows[lastRow+1].Insert(Excel.XlInsertShiftDirection.xlShiftDown, missingValue);
                    wsheet.Rows[lastRow+1].Insert(Excel.XlInsertShiftDirection.xlShiftDown, missingValue);
                    wsheet.Rows[lastRow+1].AutoFit();
                    wsheet.Rows[lastRow + 2].AutoFit();
                    lastRow += 3;
                    int row_tot = lastRow;
                    wsheet.Cells[lastRow, 5] = "=SUM(E" + StartingRow.ToString() + " : E" + (lastRow-2).ToString()+")";
                    
                    wsheet.Rows[++lastRow].Insert(Excel.XlInsertShiftDirection.xlShiftDown, missingValue);
                    wsheet.Rows[++lastRow].Insert(Excel.XlInsertShiftDirection.xlShiftDown, missingValue);
                    wsheet.Cells[lastRow, 5] = "=E" + row_tot.ToString() + "*(100-D" + lastRow.ToString() + ")/100";
                    
                    #region Commented Code
                    //wsheet.Cells[lastRow, 5] = "Totale";
                    //wsheet.Cells[lastRow, 6].NumberFormat = "#.##0,00€";

                    //wsheet.Cells[lastRow, 6] = pages[pageIndex].TotalCost; //VM.TotalCost; 

                    //wsheet.Cells[lastRow, 5].Font.Size = 12;
                    //wsheet.Cells[lastRow, 6].Font.Size = 12;

                    //wsheet.Cells[lastRow + 1, 5] = "Sconto";
                    //wsheet.Cells[lastRow + 1, 6] = 0.12;
                    //wsheet.Cells[lastRow + 1, 6].NumberFormat = "0,00%";
                    //wsheet.Cells[lastRow + 1, 5].Font.Size = 12;
                    //wsheet.Cells[lastRow + 1, 6].Font.Size = 12;

                    //wsheet.Cells[lastRow + 2, 5] = "Totale a Pagare";
                    //wsheet.Cells[lastRow + 2, 6].NumberFormat = "#.##0,00€";
                    //wsheet.Cells[lastRow + 2, 6] = "=F" + lastRow.ToString() + "* (100% - F" + (lastRow + 1).ToString() + ")";
                    //wsheet.Cells[lastRow + 2, 5].Font.Size = 12;
                    //wsheet.Cells[lastRow + 2, 6].Font.Size = 14;
                    //wsheet.Cells[lastRow + 2, 6].Font.Bold = true;

                    ////Excel.Range xlrange = 
                    //wsheet.Columns[2].Autofit();
                    //wsheet.Columns[3].Autofit();
                    //wsheet.Columns[4].Autofit();
                    //wsheet.Columns[5].Autofit();
                    //wsheet.Columns[6].Autofit();
                    
                    #endregion
                    // sets the vertical alignment for all the cells written in the loop.
                    //Excel.Range row = wsheet.get_Range("A" + (5).ToString(), "F" + (lastRow).ToString());
                    //row.Select();
                    //row.VerticalAlignment = Excel.XlVAlign.xlVAlignTop; 
                                        
                }
                //VerticalAlignment = Excel.XlVAlign.xlVAlignTop;
                
            }
            catch (Exception)
            {                
                throw;
            }
        }

        public void Print()
        {
            if (xcl!=null)
            {                
                //xcl.ActiveWorkbook.PrintOutEx(missingValue,
                //    missingValue, missingValue, false, xcl.ActivePrinter, missingValue, false, false, missingValue);
                xcl.ActiveWorkbook.PrintPreview(missingValue);
            }
        }

        public void Show()
        {
            xcl.Visible = true;
            xcl.UserControl = true;                
        }

        public void Hide()
        {
            xcl.Visible = false;
            xcl.UserControl = false;                
        }

        public void Close()
        {            
            xcl.Quit();
            Marshal.FinalReleaseComObject(xcl);
        }
    }
}
